using System;
using System.Net;
using System.Threading.Tasks;
using ErpManager.WPF.Models;

namespace ErpManager.WPF.Services
{
    public class LogService
    {
        private readonly ApplicationDbContext _context;
        private readonly string _currentUserId;
        private readonly string _currentUserName;

        public LogService(ApplicationDbContext context, string userId, string userName)
        {
            _context = context;
            _currentUserId = userId;
            _currentUserName = userName;
        }

        public async Task LogOperationAsync(string module, string operation, string details)
        {
            try
            {
                var log = new OperationLog
                {
                    UserId = _currentUserId,
                    UserName = _currentUserName,
                    Module = module,
                    Operation = operation,
                    Details = details,
                    OperationTime = DateTime.Now,
                    IpAddress = GetLocalIPAddress()
                };

                _context.OperationLogs.Add(log);
                await _context.SaveChangesAsync();
            }
            catch (Exception)
            {
                // 记录日志失败时，我们不希望影响主要业务流程
                // 可以考虑写入本地日志文件或其他备用方案
            }
        }

        private string? GetLocalIPAddress()
        {
            try
            {
                string hostName = Dns.GetHostName();
                IPAddress[] addresses = Dns.GetHostAddresses(hostName);

                foreach (IPAddress address in addresses)
                {
                    if (address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
                    {
                        return address.ToString();
                    }
                }
                return null;
            }
            catch
            {
                return null;
            }
        }
    }
}
